<?php

namespace app\api\service;

use app\admin\model\AuthGroup;
use app\api\controller\Auth;
use app\api\model\AdminModel;
use app\api\model\AuthGroupAccessModel;
use app\api\model\AuthModel;
use think\Db;
use think\Request;
use think\Validate;

class AuthService extends Api
{
    protected static $instance;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    public static function getInstance()
    {
        if (is_null(self::$instance))
        {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 创建岗位组
     */
    public function setAuthGroup($params)
    {
        $Validate = new Validate([
            'pid' => 'require',
            'name' => 'require',
            'status' => 'require',
//            'rules' => 'require',
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }

        $saveData = [
            'pid' => $params['pid'],
            'name' => $params['name'],
            'status' => $params['status'],
            'admin_id' => $this->uid,
        ];
        if (isset($params['rules']))
        {
//            $saveData['rules'] = $params['rules'];
        }
        LogService::getInstance()->writeSysLog([
            'operation' => '/api/auth/setAuthGroup',
            'title' => !empty($params['id']) ? '编辑' : '添加',
            'content' => $params,
        ]);

        if (!empty($params['id']))
        {
            $parentInfo = self::getParentInfo($params['pid']);
            if ($params['id'] == $params['pid'])
            {
                $this->error('不可设置自己为父级关系');
            }
            if ($params['pid'] != 0 && empty($parentInfo['status']) && $params['status'])
            {
                $this->error('该权限组不可用，无法启用');
            }
            $saveData['updatetime'] = time();
            return AuthModel::getInstance()->update($params['id'], $saveData);
        }
        $saveData['createtime'] = time();
        return AuthModel::getInstance()->insert($saveData);
    }

    /**
     * 获取上级信息
     */
    public function getParentInfo($pid = 0)
    {
        return AuthModel::getInstance()->find([
            'id' => ['eq', $pid]
        ]);
    }

    /**
     * 获取岗位组列表
     */
    public function getAuthList($params)
    {
        $where = [];
        if (isset($params['status']))
        {
            $where = [
                'status' => ['eq', $params['status']]
            ];
        }
        $where['id'] = ['neq', 1];

        //获取当前登录账号一级管理员
        $adminList = AdminModel::getInstance()->select([
            'id' => ['neq', 1]
        ], 'id,username,nickname,pid,level');
        //获取父级id
        $parentIds = MenuService::getInstance()->getParentIds($adminList, $this->uid);

        //获取父级添加的岗位
        $parentGroup = Db::name('auth_group')->where([
            'admin_id' => ['in', $parentIds]
        ])->column('id');
        //获取自己添加的岗位
        $thisGroup = Db::name('auth_group')->where([
            'admin_id' => ['eq', $this->uid]
        ])->column('id');
        //获取自己的岗位
        $selfGroup = AuthGroupAccessModel::getInstance()->column($this->uid);
        //取合集
        if (isset($params['status']))
        {
            $ids = array_merge($thisGroup, $selfGroup);
        }else{
            $ids = $thisGroup;
        }

        //获取下级岗位
        $groupIds = Db::name('auth_group')->field('id, pid')->select();
        $ids = MenuService::getInstance()->getChildIds($groupIds, $ids);
        $ids = MenuService::getInstance()->getChildIds($groupIds, $ids);

        $where['id'] = ['in', $ids];
        $list = AuthModel::getInstance()->getAuthList($where, 'id,pid,name');
        $pid = empty($list) ? 0 : min(array_column($list, 'pid'));
        return MenuService::getInstance()->getMenuTree($list, $pid);
    }

    /**
     * 获取指定岗位信息
     */
    public function getAuthInfo($params)
    {
        $Validate = new Validate([
            'id' => 'require'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $info = AuthModel::getInstance()->find([
            'id' => ['eq', $params['id']]
        ], 'id,pid,name,status');
        return $info;
    }

    /**
     * 获取权限组菜单
     */
    public function getAuthMenu($params)
    {
        $authRules = MenuService::getInstance()->getUserRules('id,pid,name,title');
        return $authRules;
    }

    /**
     * 设置指定岗位组权限
     */
    public function setAuthRules($params)
    {
        $Validate = new Validate([
            'gid' => 'require',
            'rules' => 'require',
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $res = AuthModel::getInstance()->update($params['gid'], [
            'rules' => $params['rules']
        ]);
        return $res;
    }

    /**
     * 指定权限
     */
    public function setGroupAuth($params)
    {
        $Validate = new Validate([
            'group' => 'require',
            'uid' => 'require',
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $uid = explode(',', $params['uid']);
        foreach ($uid as $k => $v)
        {
            AuthModel::getInstance()->delete([
                'uid' => ['eq', $v],
                'group_id' => ['eq', $params['group']]
            ]);
            $saveData[] = [
                'uid' => $v,
                'group_id' => $params['group']
            ];
        }
        return AuthModel::getInstance()->saveAll($saveData);
    }

    /**
     * 解除授权
     */
    public function uSetAuth($params)
    {
        $Validate = new Validate([
            'group' => 'require',
            'uid' => 'require'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        return AuthModel::getInstance()->delete([
            'uid' => ['eq', $params['uid']],
            'group_id' => ['eq', $params['group']]
        ]);
    }

}